local Players = game:GetService("Players")
local TweenService = game:GetService("TweenService")

local rainbowColors = {
    Color3.fromRGB(255, 0, 0),
    Color3.fromRGB(255, 127, 0),
    Color3.fromRGB(255, 255, 0),
    Color3.fromRGB(0, 255, 0),
    Color3.fromRGB(0, 0, 255),
    Color3.fromRGB(75, 0, 130),
    Color3.fromRGB(148, 0, 211)
}

local function addHatToPlayer(player)
    local character = player.Character or player.CharacterAdded:Wait()
    local head = character:WaitForChild("Head")
    if head:FindFirstChild("RainbowHat") then return end
    local hat = Instance.new("MeshPart")
    hat.Name = "RainbowHat"
    hat.MeshId = "rbxassetid://1778999"
    hat.TextureID = ""
    hat.Material = Enum.Material.ForceField
    hat.Anchored = false
    hat.CanCollide = false
    hat.Size = Vector3.new(2.5, 0.5, 2.5)
    hat.CFrame = head.CFrame * CFrame.new(0, 1.0, 0)
    hat.Parent = head
    local weld = Instance.new("WeldConstraint")
    weld.Part0 = head
    weld.Part1 = hat
    weld.Parent = hat
    local tweenInfo = TweenInfo.new(1.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)
    local function setRainbowColor()
        while hat and hat.Parent do
            for i = 1, #rainbowColors do
                local nextIndex = i % #rainbowColors + 1
                local tween = TweenService:Create(hat, tweenInfo, {Color = rainbowColors[nextIndex]})
                tween:Play()
                tween.Completed:Wait()
            end
        end
    end
    task.spawn(setRainbowColor)
end

for _, player in ipairs(Players:GetPlayers()) do
    task.spawn(function()
        local success, err = pcall(addHatToPlayer, player)
    end)
end

Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        local success, err = pcall(function()
            addHatToPlayer(player)
        end)
    end)
end)